﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Async;
using System.Xml;
using System.Xml.Serialization;
using JustinAngel.MetroBlog.Common.IoC;
using JustinAngel.MetroBlog.Models;
using JustinAngel.MetroBlog.Services.BlogPostService;
using JustinAngel.MetroBlog.Services.CategoryService;
using JustinAngel.MetroBlog.Services.Data;
using JustinAngel.MetroBlog.Services.Repository;
using JustinAngel.MetroBlog.Services.UserService;
using Microsoft.Practices.Unity;
using JustinAngel.MetroBlog.Common.Helpers;

namespace JustinAngel.MetroBlog.Controllers
{
    public class HomeController : AsyncController
    {
        public HomeController()
        {
            IoC.BuildUp(this);
        }

        [Dependency]
        public IBlogPostService BlogPostService { get; set; }

        [Dependency]
        public IRepository<Category> CategoryRepository { get; set; }

        [Dependency]
        public IUserService UserService { get; set; }

        [OutputCache(Duration = 60 * 15, VaryByParam = "none")]
        public void ShowAsync()
        {
            var defaultUser = UserService.GetUserByUserNameOrDefaultUser(null);
            AsyncManager.OutstandingOperations.Increment(2);
            GetTwitterRss(defaultUser);
            //GetTopsyFeed(defaultUser);
            GetTwitPicFeed(defaultUser);
            GetDatabaseData(defaultUser);
        }


        public ActionResult ShowCompleted(List<TwitPicModel> twitPicModels, string FirstTweet, HomeModel Model)
        {
            Model.LatestTweet = FirstTweet;
            Model.TwitPics = twitPicModels;

            ViewData["SidebarModel"] = new SidebarModel(null, Model.User.BlogTitle);
            this.SetWebsiteRoot();

            return View("Home", Model);
        }


        private void GetTwitPicFeed(User defaultUser)
        {
            FetchAndDeserializeTo<TwitPicFeedRoot>("http://api.twitpic.com/2/users/show.xml?username=" + defaultUser.TwitterUsername,
                feed =>
                {
                    List<TwitPicModel> twitPicModels = feed.Images.Select(item =>
                        {
                            var ID = item.ID;
                            var title = item.Message;
                            title = HttpUtility.HtmlDecode(title).Trim('@');
                            return new TwitPicModel()
                                {
                                    TwitPicID = ID,
                                    Title = title
                                };
                        })
                        .Where(tp => !string.IsNullOrEmpty(tp.Title)) 
                        .ToList();
                    AsyncManager.Parameters["twitPicModels"] = twitPicModels;
                    AsyncManager.OutstandingOperations.Decrement();
                });
        }



        private void GetTwitterRss(User defaultUser)
        {
            GetSyndicationFeedFor("http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=" + defaultUser.TwitterUsername,
                feed =>
                {
                    AsyncManager.Parameters["FirstTweet"] = feed.Items.First().Title.Text.Remove(defaultUser.TwitterUsername + ": ");
                    AsyncManager.OutstandingOperations.Decrement();
                });
        }

        //private void GetTopsyFeed(User defaultUser)
        //{
        //    GetSyndicationFeedFor("http://otter.topsy.com/searchdate.rss?q=justinangel.net",
        //    feed =>
        //    {
        //        foreach (var item in feed.Items)
        //        {
        //            var link = item.Links.FirstOrDefault();
        //            if (link != null)
        //            {
        //                var uri = link.GetAbsoluteUri();
        //                if (uri != null)
        //                {
        //                   .AbsoluteUri.Remove("http://justinangel.net");
        //                }

        //            }
        //        }

        //        AsyncManager.Parameters["TopsyData"] = ;
        //        AsyncManager.OutstandingOperations.Decrement();
        //    });
        //}

        private void GetDatabaseData(User defaultUser)
        {
            var model = new HomeModel()
            {
                Articles = BlogPostService.GetHomePageBlogPosts(),
                Categories = CategoryRepository.Get().ToList(),
                User = defaultUser
            };
            AsyncManager.Parameters["Model"] = model;
        }

        private void GetSyndicationFeedFor(string url, Action<SyndicationFeed> callback)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.BeginGetResponse(ac =>
                {
                    var response = webRequest.EndGetResponse(ac);
                    using (var s = response.GetResponseStream())
                    using (var r = XmlReader.Create(s))
                    {
                        var feed = SyndicationFeed.Load(r);
                        callback(feed);
                    }
                }, null);
        }

        private void FetchAndDeserializeTo<T>(string url, Action<T> callback)
        {
            var request = WebRequest.Create(url);
            request.BeginGetResponse(ar =>
            {
                using (var response = request.EndGetResponse(ar))
                using (var responseStream = response.GetResponseStream())
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    T result = (T)serializer.Deserialize(responseStream);
                    callback(result);
                }
            }, null);

        }
    }
}
